package com.itheima.youdianda.controller;

import com.itheima.youdianda.common.ResultData;
import com.itheima.youdianda.common.PageBean;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.entity.YddUser;
import com.itheima.youdianda.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/admin/ydd_user")
public class YddUserController {
    @Autowired
    public YddUserService yddUserService;
    @GetMapping("/list")
    public ResultData list(String sex, String username, String mobile, Integer page, Integer limit){
        //构造分页查询器
        Page<YddUser> pegeInfo=new Page<>(page,limit);

        //创建条件构造器
        LambdaQueryWrapper<YddUser> queryWrapper=new LambdaQueryWrapper<>();
        //模糊查询
        queryWrapper.like(username!=null,YddUser::getUsername,username);
        queryWrapper.like(sex!=null,YddUser::getSex,sex);
        queryWrapper.like(mobile!=null,YddUser::getMobile,mobile);
        //添加排序条件
        queryWrapper.orderByDesc(YddUser::getId);
        Page<YddUser> pages= yddUserService.page(pegeInfo, queryWrapper);
        PageBean<YddUser> pageBean=new PageBean<>();
        pageBean.setCount((int) pages.getTotal());
        pageBean.setCurrentPage((int)pages.getCurrent());
        pageBean.setPageSize((int)pages.getSize());
        pageBean.setTotalPages((int)pages.getPages());
        pageBean.setData(pages.getRecords());
        return ResultData.succeed("",pageBean);

    }

    /**
     * 用户管理--根据id查询单个数据
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(Integer id) {
        YddUser byId = yddUserService.getById(id);
        return ResultData.succeed(byId);
    }

    /**
     * 用户管理--根据id删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(Integer id) {

        yddUserService.removeById(id);
        return ResultData.succeed("删除成功");
    }

    /**
     * 用户管理--修改
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser) {

        yddUserService.updateById(yddUser);
        return ResultData.succeed("修改成功");
    }

    /**
     * 用户管理--添加
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddUser yddUser) {
        yddUserService.save(yddUser);
        return ResultData.succeed("添加成功");
    }
}
